//
//  MWApplicationController.m
//  XiRan-iOS
//
//  Created by Richfit on 2019/10/10.
//  Copyright © 2019 Wood. All rights reserved.
//

#import "MWApplicationController.h"
#import "MWApplicationSearchController.h"
#import "ApplicationInfoViewController.h"

#import "MWApplicationCell.h"

@interface MWApplicationController () <UITableViewDataSource, UITableViewDelegate>

@property(nonatomic, strong) UITableView *tableView;

@property(nonatomic, assign) NSInteger page;
@property(nonatomic, assign) NSInteger size;
@property(nonatomic, assign) MWRequestMode requestMode;

@property(strong, nonatomic) NSMutableArray *appArray;

@end

@implementation MWApplicationController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = [[MWConfigManager manager] objectForKey:@"application_title" defaultValue:@"应用场景"];
    [self setupPageSubviews];
    
    [_tableView.mj_header beginRefreshing];
}

-(void)searchAvtion:(UIButton *)sender {
    MWApplicationSearchController *controller = [[MWApplicationSearchController alloc] init];
    [self.navigationController pushViewController:controller animated:YES];
}

#pragma mark - 应用场景数据
- (void)refreshApplication {
    _page = 1;
    _size = 10;
    _requestMode = MWRequestModeRefresh;
    [self loadApplicationWithSearch:@"" page:_page size:_size];
}

- (void)loadMoreApplication {
    _page++;
    _size = 10;
    _requestMode = MWRequestModeLoadMore;
    [self loadApplicationWithSearch:@"" page:_page size:_size];
}

- (void)loadApplicationWithSearch:(NSString *)search page:(NSInteger)page size:(NSInteger)size {
    NSString *token = [MWUserManager manager].user.token;
    NSMutableDictionary *paraDic = [[NSMutableDictionary alloc] init];
    [paraDic setObject:token forKey:@"token"];
    [paraDic setObject:search forKey:@"search"];
    [paraDic setObject:[NSString stringWithFormat:@"%ld", (long)page] forKey:@"page"];
    [paraDic setObject:[NSString stringWithFormat:@"%ld", (long)size] forKey:@"size"];
    [paraDic setObject:[MWConfigManager manager].productType forKey:@"is_material"];
    [paraDic setObject:[MWConfigManager manager].language forKey:@"language"];

    MWWeakSelf
    [[MWNetworkManager manager] POST:kApplicationUrl parameters:paraDic progress:^(NSProgress *downloadProgress) {
        
    } success:^(id responseObject) {
        NSDictionary *dic = responseObject;
        NSInteger code = [[dic objectForKey:@"code"] integerValue];
        
        if (code == 1) {
            NSArray *tempArray = [MWApplicationModel mj_objectArrayWithKeyValuesArray:[dic objectForKey:@"data"]];
            if (weakSelf.requestMode == MWRequestModeRefresh) {
                [weakSelf.tableView.mj_header endRefreshing];
                [weakSelf.appArray removeAllObjects];
            } else {
                if (tempArray.count <= 0) {
                    self->_page--;
                    [weakSelf.tableView.mj_footer endRefreshing];
                } else {
                    [weakSelf.tableView.mj_footer endRefreshing];
                }
            }
            
            [self.appArray addObjectsFromArray:tempArray];
            [weakSelf.tableView reloadData];
            
        } else {
            [weakSelf.tableView.mj_header endRefreshing];
            [weakSelf.tableView.mj_footer endRefreshing];
        }
        
    } failure:^(NSError *error) {
        [weakSelf.tableView.mj_header endRefreshing];
        [weakSelf.tableView.mj_footer endRefreshing];
    }];
}

#pragma mark - UITableViewDataSource && UITableViewDelegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if ([MWConfigManager manager].isNetError) {
        self.errorTitleLabel.text = [[MWConfigManager manager] objectForKey:@"click_retry" defaultValue:@"点击重试"];
        self.errorTitleLabel.hidden = self.errorImageView.hidden = NO;
        tableView.hidden = YES;
    } else if (!self.appArray.count) {
        if (self.isFirst) {
            
        } else {
            self.errorTitleLabel.text = [[MWConfigManager manager] objectForKey:@"nodata" defaultValue:@"暂无数据"];
            self.errorTitleLabel.hidden = self.errorImageView.hidden = NO;
            tableView.hidden = YES;
        }

    } else {
        self.errorTitleLabel.hidden = self.errorImageView.hidden = YES;
        tableView.hidden = NO;
    }
    return self.appArray.count;
}


- (void)refresh {
    [super refresh];
    [self.tableView.mj_header beginRefreshing];
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 0.1f;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 0.1f;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    return [[UIView alloc] initWithFrame:CGRectZero];
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    return [[UIView alloc] initWithFrame:CGRectZero];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *identifier = @"MWApplicationCell";
    MWApplicationCell *applicationCell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (!applicationCell) {
        applicationCell = [[MWApplicationCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
        applicationCell.selectionStyle = UITableViewCellSelectionStyleNone;
    }
    [applicationCell setupData:self.appArray[indexPath.row]];
//    applicationCell.delegate = self;
    return applicationCell;
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    ApplicationInfoViewController *aic = [[ApplicationInfoViewController alloc] init];
    MWApplicationModel *application = self.appArray[indexPath.row];
    aic.showroomArray = [NSMutableArray arrayWithArray:application.images];
    aic.navTitleString = application.content;
    [self.navigationController pushViewController:aic animated:YES];
}

//- (void)collectionViewItwmClickWith:(NSMutableArray *)dataArray contentTitle:(nonnull NSString *)navTitleString {
//    ApplicationInfoViewController *aic = [[ApplicationInfoViewController alloc] init];
//    aic.showroomArray = dataArray;
//    aic.navTitleString = navTitleString;
//    [self.navigationController pushViewController:aic animated:YES];
//}

- (NSMutableArray *)appArray {
    if (!_appArray) {
        _appArray = [[NSMutableArray alloc] init];
    }
    
    return _appArray;
}

#pragma mark - UI
- (void)setupPageSubviews {
    UIButton *searchBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    searchBtn.frame = CGRectMake(0, 0, 20, 20);
    [searchBtn setImage:[UIImage imageNamed:@"ic_search_white"] forState:UIControlStateNormal];
    [searchBtn setImage:[UIImage imageNamed:@"ic_search_white"] forState:UIControlStateHighlighted];
    [searchBtn addTarget:self action:@selector(searchAvtion:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *buttonItem = [[UIBarButtonItem alloc] initWithCustomView:searchBtn];
    self.navigationItem.rightBarButtonItem = buttonItem;
    
    _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
    _tableView.backgroundColor = [UIColor whiteColor];
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    _tableView.rowHeight = UITableViewAutomaticDimension;
    _tableView.estimatedRowHeight = 300;
    _tableView.dataSource = self;
    _tableView.delegate = self;
    [self.view addSubview:_tableView];
    
    [_tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.view);
    }];
    _tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [self refreshApplication];
    }];
    
    _tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        //Call this Block When enter the refresh status automatically
        [self loadMoreApplication];
    }];
    
}


@end
